<?php
/**
 * @package Autogenerator for Joomla!
 * @version 3.0.0
 * @author Truong Cong Duc <truongcongduc4@gmail.com>
 * @link autogenerator.blogspot.com
 * @copyright (c) 2013, Truong Cong Duc
 * @license GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

defined('DS') or define('DS', DIRECTORY_SEPARATOR);

jimport('joomla.filesystem.folder');

JLoader::register('VariableHelper', AUTOGENERATOR_DIR_ROOT . '/helpers/variable.php');
JLoader::register('ConstantHelper', AUTOGENERATOR_DIR_ROOT . '/helpers/constant.php');

class AutogeneratorHelper {

    public static $aAdminLanguage = array();
    public static $aAdminLanguageSystem = array();
    public static $aFrontendLanguage = array();
    public static $aFrontendLanguageSystem = array();
    public static $aAllXMLTypes;
    public static $aAllSelectedTables;
    public static $extension = 'com_autogenerator';

    public static function addSubmenu($vName) {
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_COMPONENTS'), 'index.php?option=com_autogenerator&view=components', $vName == 'components'
        );
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_TABLES'), 'index.php?option=com_autogenerator&view=tables', $vName == 'tables'
        );
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_FIELDS'), 'index.php?option=com_autogenerator&view=fields', $vName == 'fields'
        );
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_MVCS'), 'index.php?option=com_autogenerator&view=mvcs', $vName == 'mvcs'
        );
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_XML_TYPES'), 'index.php?option=com_autogenerator&view=xml_types', $vName == 'xml_types'
        );
        JHtmlSidebar::addEntry(
                JText::_('JAUTOGENERATOR_XML_ATTRIBUTES'), 'index.php?option=com_autogenerator&view=xml_attributes', $vName == 'xml_attributes'
        );
    }

    /**
     * 
     * @param string $sContent
     * @param array $aParams
     * @return string Content.
     */
    public static function replaceCodeTemplate($sContent, $aParams) {
        $aVariables = array();
        // Add variables for parameters.
        foreach ($aParams as $sKey => $sValue) {
            $aVariables['{$' . $sKey . '}'] = $sValue;
            $aVariables['{$' . $sKey . '|capitalize}'] = ucfirst(strtolower($sValue));
            $aVariables['{$' . $sKey . '|lower}'] = strtolower($sValue);
            $aVariables['{$' . $sKey . '|upper}'] = strtoupper($sValue);
        }
        // Replace content.
        $aFrom = array_keys($aVariables);
        $aTo = array_values($aVariables);
        return str_replace($aFrom, $aTo, $sContent);
    }

    static function getAllMVCsByTableId($iTableId, $iType = 3) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('am.*')
                ->from('#__auto_mvc AS am')
                ->join('LEFT', '#__auto_table AS at ON at.id = am.table_id')
                ->join('LEFT', '#__auto_component AS ac ON ac.id = at.component_id')
                ->where('ac.id IN (SELECT component_id FROM #__auto_table WHERE id = ' . (int) $iTableId . ' AND status = 1)')
                ->where('ac.status = 1');

        if ($iType != 3) {
            $query->where('am.type = ' . (int) $iType);
        }

        $db->setQuery($query);

        try {
            $aTables = $db->loadObjectList();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage());
        }

        return $aTables;
    }

    public static function getMVCsByTableId($iTableId, $iType = 3) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('am.*')
                ->from('#__auto_mvc AS am')
                ->join('LEFT', '#__auto_table AS at ON at.id = am.table_id')
                ->where('at.id = ' . (int) $iTableId)
                ->where('at.status = 1');

        if ($iType != 3) {
            $query->where('am.type = ' . (int) $iType);
        }

        $db->setQuery($query);

        try {
            $aMVCs = $db->loadObject();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        return $aMVCs;
    }

    public static function getAllMVCsByComponentId($iComponentId, $iType = 3) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('am.*')
                ->from('#__auto_mvc AS am')
                ->join('LEFT', '#__auto_table AS at ON at.id = am.table_id')
                ->join('LEFT', '#__auto_component AS ac ON ac.id = at.component_id')
                ->where('ac.id = ' . (int) $iComponentId)
                ->where('ac.status = 1')
                ->where('at.status = 1');

        if ($iType != 3) {
            $query->where('am.type = ' . (int) $iType);
        }
        
        $db->setQuery($query);

        try {
            $aMVCs = $db->loadObjectList();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        return $aMVCs;
    }

    static function getAllTablesByComponentId($iComponentId) {
        self::$aAllSelectedTables = null;

        if (self::$aAllSelectedTables) {
            return self::$aAllSelectedTables;
        } else {
            $db = JFactory::getDbo();
            $query = $db->getQuery(true);

            $query->select('at.*')
                    ->from('#__auto_table AS at')
                    ->join('LEFT', '#__auto_component AS ac ON ac.id = at.component_id')
                    ->where('at.component_id = ' . (int) $iComponentId);

            $db->setQuery($query);

            try {
                self::$aAllSelectedTables = $db->loadObjectList();
            } catch (RuntimeException $e) {
                JError::raiseWarning(500, $e->getMessage);
            }

            return self::$aAllSelectedTables;
        }
    }

    public static function getAvailableComponentIds() {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('ac.id')
                ->from('#__auto_component AS ac')
                ->where('ac.status = 1');

        $db->setQuery($query);

        try {
            $aComponents = $db->loadColumn();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        return $aComponents;
    }

    public static function getExtraContent($sFilePath) {
        if (JFile::exists($sFilePath)) {
            return file_get_contents($sFilePath);
        } else {
            echo 'error path: ' . $sFilePath;
            die;
        }
    }

    public static function getSqlInstallContent($iComponentId) {
        $aTables = AutogeneratorHelper::getAllTablesByComponentId($iComponentId);
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        // Get sql template.
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'sql' .
                DS . 'install.mysql.utf8.sql.tpl';
        $sSqlTemplate = AutogeneratorHelper::getExtraContent($sFilePath);
        // Get sql tables.
        $aSqlTables = array();
        foreach ($aTables as $oTable) {
            $aFields = $oModelFields->getFields($oTable->id);
            $aSqlFields = array();
            foreach ($aFields as $oField) {
                $aSqlFields[] = '`' . $oField->sql_field . '` ' . $oField->sql_type . ($oField->sql_null == 'NO' ? ' NOT NULL' : '') . (empty($oField->sql_default) ? '' : ' DEFAULT "' . $oField->sql_default . '"') . ($oField->sql_key == 'PRI' ? ' PRIMARY KEY' : '') . (empty($oField->sql_extra) && $oField->sql_extra == 'auto_increment' ? '' : ' ' . strtoupper($oField->sql_extra));
            }
            $sSqlTable = implode(',' . chr(13), $aSqlFields);

            if (!empty($sSqlTable)) {
                $aFrom = array('{$AUTO_GENERATOR_SQL_TABLE_NAME}', '{$AUTO_GENERATOR_SQL_FIELDS}');
                $aTo = array($oTable->sql_table_name, $sSqlTable);
                $aSqlTables[] = str_replace($aFrom, $aTo, $sSqlTemplate);
            }
        }
        return implode(chr(13), $aSqlTables);
    }

    public static function getHelperContent($iComponentId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'helpers' .
                DS . 'helper.php.tpl';

        $sSubMenus = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'helpers' .
                DS . 'include_submenu.php.tpl';
        
        $sSubMenuTemplate = AutogeneratorHelper::getExtraContent($sSubMenus);

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oComponent = $oModelComponent->getItem($iComponentId);

        $aMVCs = AutogeneratorHelper::getAllMVCsByComponentId($iComponentId, ConstantHelper::$_MVC_TYPE_LIST);

        $aIncludeSubMenu = array();
        foreach ($aMVCs as $oMVC) {
            $aParams = array(
                'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                'AUTO_GENERATOR_VIEWS' => $oMVC->title
            );

            self::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_SUBMENU_'. strtoupper($oMVC->title)] = $oMVC->title;
            
            $aIncludeSubMenu[] = self::replaceCodeTemplate($sSubMenuTemplate, $aParams);
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_INCLUDE_HELPER_SUBMENU' => implode(chr(13), $aIncludeSubMenu)
        );

        return self::replaceCodeTemplate(self::getExtraContent($sFilePath), $aParams);
    }

    public static function getSqlUninstallContent($iComponentId) {
        $aTables = AutogeneratorHelper::getAllTablesByComponentId($iComponentId);
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        // Get sql template.
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'sql' .
                DS . 'uninstall.mysql.utf8.sql.tpl';
        // Get sql tables.
        $aSqlTables = array();
        foreach ($aTables as $oTable) {
            $aFields = $oModelFields->getFields($oTable->id);
            if ($aFields) {
                $aSqlTables[] = str_replace('{$AUTO_GENERATOR_SQL_TABLE_NAME}', $oTable->sql_table_name, AutogeneratorHelper::getExtraContent($sFilePath));
            }
        }
        return implode(chr(13), $aSqlTables);
    }

    public static function getAdminFormViewHTMLContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'views' .
                DS . 'view' .
                DS . 'view.html.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_VIEW' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendItemViewHTMLContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'views' .
                DS . 'view' .
                DS . 'view.html.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvcItem = $oModelMvc->getItem($iMvcId);
        if ($oMvcItem->id == 0) {
            return '';
        }
        $oMvcList = self::getMVCsByTableId($oMvcItem->table_id, ConstantHelper::$_MVC_TYPE_LIST);
        if ($oMvcList->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcItem->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvcItem->title,
            'AUTO_GENERATOR_VIEW' => $oMvcItem->title,
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminModelsContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'models' .
                DS . 'models.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');

        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $aFields = $oModelFields->getFields($oTable->id);
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvc->table_id);

        $aFilterField = array();
        foreach ($aFields as $aField) {
            $aFilterField[] = "'" . $aField->sql_field . "'";
        }
        $sFilterFields = implode(',', $aFilterField);

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_MODELS' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_SQL_TABLE_NAME' => $oTable->sql_table_name,
            'AUTO_GENERATOR_MODELS_FILTER_FIELDS' => $sFilterFields,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendControllersContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'controllers' .
                DS . 'controllers.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');

        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }

        $oMVCItem = self::getMVCsByTableId($oMvc->table_id, ConstantHelper::$_MVC_TYPE_FORM);

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_MODEL' => $oMVCItem->title,
            'AUTO_GENERATOR_CONTROLLERS' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(self::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminControllersContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'controllers' .
                DS . 'controllers.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');

        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }

        $oMVCItem = self::getMVCsByTableId($oMvc->table_id, ConstantHelper::$_MVC_TYPE_FORM);

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_MODEL' => $oMVCItem->title,
            'AUTO_GENERATOR_CONTROLLERS' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(self::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminModelContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'models' .
                DS . 'model.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_MODEL' => $oMvc->title,
            'AUTO_GENERATOR_XML_FORM' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_TABLE_TITLE' => $oTable->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminXMLFormContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'models' .
                DS . 'forms' .
                DS . 'form.xml.tpl';

        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }

        $aItems = $oModelFields->getFields($oMvc->table_id);
        $aXMLFields = array();
        foreach ($aItems as $oItem) {
            $aXMLFields[] = $oItem->xml_export_html;
        }
        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_XML_ELEMENT' => implode(chr(13), $aXMLFields),
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendControllerContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'controllers' .
                DS . 'controller.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminControllerContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'controllers' .
                DS . 'controller.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oListMVC = self::getMVCsByTableId($oTable->id, ConstantHelper::$_MVC_TYPE_LIST);
        if (!$oListMVC) {
            return '';
        }
        
        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_VIEWS' => $oListMVC->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminFormEditContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'views' .
                DS . 'view' .
                DS . 'tmpl' .
                DS . 'edit.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');

        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvc->table_id);
        // Get template for fields.
        $sIncludeFieldPath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'views' .
                DS . 'view' .
                DS . 'tmpl' .
                DS . 'include_field.php.tpl';
        $aAllFields = $oModelFields->getFields($oMvc->table_id);
        $sIncludeField = '';
        foreach ($aAllFields as $oField) {
            $sIncludeField .= self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sIncludeFieldPath), array('AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field));
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_VIEW' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
            'AUTO_GENERATOR_INCLUDE_FORM_ELEMENT' => $sIncludeField
        );

        AutogeneratorHelper::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvc->title) . '_DETAILS'] = ucfirst($oMvc->title) . ' Details';
        
        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminListViewHTMLContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'views' .
                DS . 'views' .
                DS . 'view.html.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $oMvcList = $oModelMvc->getItem($iMvcId);
        if ($oMvcList->id == 0) {
            return '';
        }
        $oMvcForm = self::getMVCsByTableId($oMvcList->table_id, ConstantHelper::$_MVC_TYPE_FORM);
        if ($oMvcForm->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcList->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvcList->table_id);

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvcForm->title,
            'AUTO_GENERATOR_CONTROLLERS' => $oMvcList->title,
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!'
        );

        AutogeneratorHelper::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_TITLE'] = $oMvcList->title;
        AutogeneratorHelper::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_MESSAGE_CONFIRM_DELETE'] = 'Delete';
        
        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getAdminListDefaultContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                DS . 'views' .
                DS . 'views' .
                DS . 'tmpl' .
                DS . 'default.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oMvcList = $oModelMvc->getItem($iMvcId);

        if ($oMvcList->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcList->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oMvcForm = self::getMVCsByTableId($oTable->id, ConstantHelper::$_MVC_TYPE_FORM);
        if ($oMvcForm->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvcList->table_id);
        $oOrderingField = self::getOrderingFieldOfTable($oTable->id);
        
        $aFields = $oModelFields->getFields($oTable->id);
        $sTemplateItems = '';
        $sTemplateHeaders = '';
        if ($aFields) {
            $sPathHeader = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_header.php.tpl';
            $sIncludeHeader = AutogeneratorHelper::getExtraContent($sPathHeader);
            $aTemplateHeader = array();
            foreach ($aFields as $oField) {
                if ($oField->is_ordering_field == 1) {
                    continue;
                }
                $aParams = array(
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
                    'AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field
                );
                
                AutogeneratorHelper::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_HEADER_' . strtoupper($oField->sql_field)] = $oField->sql_field;
                
                $aTemplateHeader[] = self::replaceCodeTemplate($sIncludeHeader, $aParams);
            }

            $sTemplateHeaders = implode(chr(13), $aTemplateHeader);

            $sPathItem = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_item.php.tpl';
            $sPathItemEdit = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_item_edit.php.tpl';
            $sIncludeItem = AutogeneratorHelper::getExtraContent($sPathItem);
            $sIncludeItemEdit = AutogeneratorHelper::getExtraContent($sPathItemEdit);
            $aTemplateItem = array();
            foreach ($aFields as $oField) {
                if ($oField->is_ordering_field == 1) {
                    continue;
                }
                $aParams = array(
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_CONTROLLER' => $oMvcForm->title,
                    'AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field,
                    'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
                );
                if ($oField->allow_edit_in_list) {
                    $aTemplateItem[] = self::replaceCodeTemplate($sIncludeItemEdit, $aParams);
                } else {
                    $aTemplateItem[] = self::replaceCodeTemplate($sIncludeItem, $aParams);
                }
            }
            $sTemplateItems = implode(chr(13), $aTemplateItem);
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvcForm->title,
            'AUTO_GENERATOR_CONTROLLERS' => $oMvcList->title,
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
            'AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_HEADER' => '',
            'AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_ITEM' => '',
            'AUTO_GENERATOR_INCLUDE_ORDERING_SETTING' => '',
            'AUTO_GENERATOR_INCLUDE_LIST_HEADER' => $sTemplateHeaders,
            'AUTO_GENERATOR_INCLUDE_LIST_ITEM' => $sTemplateItems
        );
        
        if ($oOrderingField) {
            $sPathOrderingSetting = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_ordering_setting.php.tpl';
            $sIncludeOrderingSetting = AutogeneratorHelper::getExtraContent($sPathOrderingSetting);
            $sTemplateOrderingSetting = self::replaceCodeTemplate($sIncludeOrderingSetting, array(
                'AUTO_GENERATOR_ORDERING_FIELD' => $oOrderingField->sql_field,
                'AUTO_GENERATOR_CONTROLLERS' => $oMvcList->title,
                'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
                'AUTO_GENERATOR_COMPONENT' => $oComponent->title
            ));
            
            
            $sPathOrderingHeader = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_ordering_header.php.tpl';
            $sIncludeOrderingHeader = AutogeneratorHelper::getExtraContent($sPathOrderingHeader);
            $sTemplateOrderingHeader = self::replaceCodeTemplate($sIncludeOrderingHeader, array('AUTO_GENERATOR_SQL_ORDERING_FIELD_NAME' => $oOrderingField->sql_field));
            $aParams['AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_HEADER'] = $sTemplateOrderingHeader;

            $sPathOrderingItem = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_ordering_item.php.tpl';
            $sIncludeOrderingItem = AutogeneratorHelper::getExtraContent($sPathOrderingItem);
            $sTemplateOrderingItem = self::replaceCodeTemplate($sIncludeOrderingItem, array('AUTO_GENERATOR_SQL_ORDERING_FIELD_NAME' => $oOrderingField->sql_field));
            $aParams['AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_ITEM'] = $sTemplateOrderingItem;
            $aParams['AUTO_GENERATOR_INCLUDE_ORDERING_SETTING'] = $sTemplateOrderingSetting;
        }

        AutogeneratorHelper::$aAdminLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_FILTER_SEARCH_DESC'] = 'Search sql field.';
        
        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendItemDefaultContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'views' .
                DS . 'view' .
                DS . 'tmpl' .
                DS . 'default.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oMvcList = $oModelMvc->getItem($iMvcId);
        if ($oMvcList->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcList->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oMvcItem = self::getMVCsByTableId($oMvcList->table_id, ConstantHelper::$_MVC_TYPE_ITEM);
        if ($oMvcItem->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $aFields = $oModelFields->getFields($oTable->id);
        $sTemplateField = '';
        if ($aFields) {
            $sPathField = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                    DS . 'views' .
                    DS . 'view' .
                    DS . 'tmpl' .
                    DS . 'include_item.php.tpl';
            $sIncludeField = AutogeneratorHelper::getExtraContent($sPathField);
            $aTemplateField = array();
            foreach ($aFields as $oField) {
                $aParams = array(
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field
                );
                
                AutogeneratorHelper::$aFrontendLanguage['COM_' . strtoupper($oComponent->title) . '_FORM_' . strtoupper($oField->sql_field) . '_TITLE'] = $oField->sql_field;
                
                $aTemplateField[] = self::replaceCodeTemplate($sIncludeField, $aParams);
            }
            $sTemplateField = implode(chr(13), $aTemplateField);
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_VIEW' => $oMvcList->title,
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_INCLUDE_FRONTEND_FORM_FIELD' => $sTemplateField
        );
        
        AutogeneratorHelper::$aFrontendLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_TITLE'] = $oMvcList->title;

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendListDefaultContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'views' .
                DS . 'views' .
                DS . 'tmpl' .
                DS . 'default.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oMvcList = $oModelMvc->getItem($iMvcId);
        if ($oMvcList->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcList->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oMvcItem = self::getMVCsByTableId($oMvcList->table_id, ConstantHelper::$_MVC_TYPE_ITEM);
        if ($oMvcItem->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvcList->table_id);
        if (!$oPrimaryField || $oPrimaryField->id == 0) {
            return 'Primary key is not valid!';
        }
        $aFields = $oModelFields->getFields($oTable->id);
        $sTemplateItems = '';
        $sTemplateHeaders = '';
        if ($aFields) {
            $sPathHeader = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_header.php.tpl';
            $sIncludeHeader = AutogeneratorHelper::getExtraContent($sPathHeader);
            $aTemplateHeader = array();
            foreach ($aFields as $iKey => $oField) {
                $aParams = array(
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
                    'AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field,
                    'AUTO_GENERATOR_FIELD_CSS' => ($iKey < 5 ? 'div-cell' : 'hidden')
                );
                
                AutogeneratorHelper::$aFrontendLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_HEADER_' . strtoupper($oField->sql_field)] = $oField->sql_field;
                
                $aTemplateHeader[] = self::replaceCodeTemplate($sIncludeHeader, $aParams);
            }

            $sTemplateHeaders = implode(chr(13), $aTemplateHeader);

            $sPathItem = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_item.php.tpl';
            $sIncludeItem = AutogeneratorHelper::getExtraContent($sPathItem);
            $sPathItemDetails = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                    DS . 'views' .
                    DS . 'views' .
                    DS . 'tmpl' .
                    DS . 'include_item_details.php.tpl';
            $sIncludeItemDetails = AutogeneratorHelper::getExtraContent($sPathItemDetails);
            $aTemplateItem = array();
            foreach ($aFields as $iKey => $oField) {
                $aParams = array(
                    'AUTO_GENERATOR_SQL_FIELD_NAME' => $oField->sql_field,
                    'AUTO_GENERATOR_FIELD_CSS' => ($iKey < 5 ? 'div-cell' : 'hidden'),
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_VIEW' => $oMvcItem->title,
                    'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!'
                );

                if ($oField->allow_edit_in_list) {
                    $aTemplateItem[] = self::replaceCodeTemplate($sIncludeItemDetails, $aParams);
                } else {
                    $aTemplateItem[] = self::replaceCodeTemplate($sIncludeItem, $aParams);
                }
            }
            $sTemplateItems = implode(chr(13), $aTemplateItem);
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvcItem->title,
            'AUTO_GENERATOR_CONTROLLERS' => $oMvcList->title,
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
            'AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_HEADER' => '',
            'AUTO_GENERATOR_INCLUDE_ORDERING_FIELD_ITEM' => '',
            'AUTO_GENERATOR_INCLUDE_FRONTEND_HEADER' => $sTemplateHeaders,
            'AUTO_GENERATOR_INCLUDE_FRONTEND_FIELD' => $sTemplateItems
        );

        AutogeneratorHelper::$aFrontendLanguage['COM_' . strtoupper($oComponent->title) . '_CLICK_TO_VIEW_DETAILS'] = 'Click to view details';
        AutogeneratorHelper::$aFrontendLanguage['COM_' . strtoupper($oComponent->title) . '_' . strtoupper($oMvcList->title) . '_TITLE'] = $oMvcList->title;
        
        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendModelsContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'models' .
                DS . 'models.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oModelFields = JModelLegacy::getInstance('Fields', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');

        $oMvc = $oModelMvc->getItem($iMvcId);
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $aFields = $oModelFields->getFields($oTable->id);
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvc->table_id);
        if (!$oPrimaryField) {
            return 'Primary key is not valid!';
        }
        $aFilterField = array();
        foreach ($aFields as $aField) {
            $aFilterField[] = "'" . $aField->sql_field . "'";
        }
        $sFilterFields = implode(',', $aFilterField);

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_MODELS' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_SQL_TABLE_NAME' => $oTable->sql_table_name,
            'AUTO_GENERATOR_MODELS_FILTER_FIELDS' => $sFilterFields,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!',
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendModelContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'models' .
                DS . 'model.php.tpl';

        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvc = $oModelMvc->getItem($iMvcId);
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        if ($oMvc->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvc->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }
        $oPrimaryField = $oModelField->getPrimaryKeyField($oMvc->table_id);
        if (!$oPrimaryField || $oPrimaryField->id == 0) {
            return 'Primary key is not valid!';
        }
        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_CONTROLLER' => $oMvc->title,
            'AUTO_GENERATOR_MODEL' => $oMvc->title,
            'AUTO_GENERATOR_XML_FORM' => $oMvc->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
            'AUTO_GENERATOR_TABLE_TITLE' => $oTable->title,
            'AUTO_GENERATOR_SQL_TABLE_NAME' => $oTable->sql_table_name,
            'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!'
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function getFrontendListViewHTMLContent($iMvcId) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                DS . 'views' .
                DS . 'views' .
                DS . 'view.html.php.tpl';
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelMvc = JModelLegacy::getInstance('Mvc', 'AutogeneratorModel');
        $oMvcList = $oModelMvc->getItem($iMvcId);
        if ($oMvcList->id == 0) {
            return '';
        }
        $oTable = $oModelTable->getItem($oMvcList->table_id);
        if ($oTable->id == 0) {
            return '';
        }
        $oComponent = $oModelComponent->getItem($oTable->component_id);
        if ($oComponent->id == 0) {
            return '';
        }

        $aParams = array(
            'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
            'AUTO_GENERATOR_VIEWS' => $oMvcList->title,
            'AUTO_GENERATOR_COMPONENT' => $oComponent->title
        );

        return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
    }

    public static function createFolder($sFolder) {
        $oApp = JFactory::getApplication('administrator');
        $sFullFolder = $oApp->getCfg('tmp_path') . (empty($sFolder) ? DS . 'error_path' : DS . $sFolder);
        
        if (!JFolder::exists($sFullFolder)) {
            return JFolder::create($sFullFolder, 0777);
        }
        
        return true;
    }
    
    public static function copyIndexHTML($sFolder) {
        $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' . DS . 'index.html';
        $oApp = JFactory::getApplication('administrator');
        $sFullFolder = $oApp->getCfg('tmp_path') . (empty($sFolder) ? DS . 'error_path' : DS . $sFolder);
        
        if (JFile::exists($sFilePath) && JFolder::exists($sFullFolder)){
            
            if (JFile::exists($sFullFolder . DS . 'index.html')) {
                chmod($sFullFolder . DS . 'index.html', 0777);
                return;
            }
            
            if (JFile::copy($sFilePath, $sFullFolder . DS . 'index.html')) {
                chmod($sFullFolder . DS . 'index.html', 0777);
            }
        }
    }
    
    public static function getContentFileInTemplate($sFileName, $sType = 'list', $bIsAdmin = true, $bIsMain = false) {
        switch ($sFileName) {
            case 'view.html.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'views' .
                        DS . ($sType == 'list' ? 'views' : 'view') .
                        DS . 'view.html.php.tpl';
                break;
            case 'default.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'views' .
                        DS . 'views' .
                        DS . 'tmpl' .
                        DS . 'default.php.tpl';
                break;
            case 'model.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'models' .
                        DS . 'model.php.tpl';
                break;
            case 'models.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'models' .
                        DS . 'models.php.tpl';
                break;
            case 'controller.php':
                if ($bIsMain) {
                    $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                            DS . 'controller.php.tpl';
                } else {
                    $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                            DS . 'controllers' .
                            DS . 'controller.php.tpl';
                }
                break;
            case 'controllers.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'controllers' .
                        DS . 'controllers.php.tpl';
                break;
            case 'edit.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'views' .
                        DS . 'view' .
                        DS . 'tmpl' .
                        DS . 'edit.php.tpl';
                break;
            case 'form.xml':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'models' .
                        DS . 'forms' .
                        DS . 'form.xml.tpl';
                break;
            case 'table.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'tables' .
                        DS . 'table.php.tpl';
                break;
            case 'access.xml':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'access.xml.tpl';
                break;
            case 'component.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . ($bIsAdmin ? 'administrator' : 'frontend') .
                        DS . 'component.php.tpl';
                break;
            case 'component.xml':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'component.xml.tpl';
                break;
            case 'config.xml':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'config.xml.tpl';
                break;
            case 'install.mysql.utf8.sql':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'sql' .
                        DS . 'install.mysql.utf8.sql.tpl';
                break;
            case 'uninstall.mysql.utf8.sql':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'sql' .
                        DS . 'uninstall.mysql.utf8.sql.tpl';
                break;
            case 'metadata.xml':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                        DS . 'metadata.xml.tpl';
                break;
            case 'router.php':
                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'frontend' .
                        DS . 'router.php.tpl';
                break;
            default:
                $sFilePath = '';
                break;
        }
        if (JFile::exists($sFilePath)) {
            $sContent = file_get_contents($sFilePath);
        } else {
            echo 'error path: ' . $sFilePath;
            die;
        }
        // Compile variables.
        $sContent = self::replaceCodeTemplate($sContent, VariableHelper::$_VARIABLES);

        return $sContent;
    }

    public static function getTableContent($iTableId) {
        $oModelTable = JModelLegacy::getInstance('Table', 'AutogeneratorModel');
        $oModelComponent = JModelLegacy::getInstance('Component', 'AutogeneratorModel');
        $oModelField = JModelLegacy::getInstance('Field', 'AutogeneratorModel');
        // Get table data.
        $oTable = $oModelTable->getItem($iTableId);
        if ($oTable) {
            $oComponent = $oModelComponent->getItem($oTable->component_id);
            if ($oComponent) {
                $oPrimaryField = $oModelField->getPrimaryKeyField($iTableId);
                $aParams = array(
                    'AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE' => '/* ' . $oComponent->copyright . ' */',
                    'AUTO_GENERATOR_SQL_TABLE_NAME' => $oTable->sql_table_name,
                    'AUTO_GENERATOR_TABLE_TITLE' => $oTable->title,
                    'AUTO_GENERATOR_COMPONENT' => $oComponent->title,
                    'AUTO_GENERATOR_PRIMARY_KEY_FIELD' => isset($oPrimaryField->sql_field) ? $oPrimaryField->sql_field : 'Primary key is not valid!'
                );

                $sFilePath = AUTOGENERATOR_DIR_CODE_TEMPLATE . 'administrator' .
                        DS . 'tables' .
                        DS . 'table.php.tpl';
                return self::replaceCodeTemplate(AutogeneratorHelper::getExtraContent($sFilePath), $aParams);
            }
        }
        return '';
    }

    public static function getAllXMLTypes() {
        if (self::$aAllXMLTypes) {
            return self::$aAllXMLTypes;
        }

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('axt.id AS value, axt.title AS text')
                ->from('#__auto_xml_type AS axt')
                ->order('axt.title ASC');

        $db->setQuery($query);

        try {
            self::$aAllXMLTypes = $db->loadObjectList();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        return self::$aAllXMLTypes;
    }

    /**
     * Search xml type.
     * @param string $sType
     * @return int
     */
    public static function searchXMLType($sType) {
        $aAllXMLTypes = AutogeneratorHelper::getAllXMLTypes();

        foreach ($aAllXMLTypes as $oXMLType) {
            $bResult = strpos(strtolower($oXMLType->text), $sType);
            if ($bResult !== false) {
                return $oXMLType->value;
            }
        }

        return 0;
    }

    public static function addButtonCustom($sMessage = '', $task = '', $icon = '', $iconOver = '', $alt = '', $listSelect = true) {
        $bar = JToolbar::getInstance('toolbar');

        // Strip extension.
        $icon = preg_replace('#\.[^.]*$#', '', $icon);

        // Add a standard button.
        $bar->appendButton('Confirm', $sMessage, $icon, $alt, $task, $listSelect);
    }

    public static function deleteFolder($sPath) {
        $oApp = JFactory::getApplication('administrator');
        $sRootFolder = $oApp->getCfg('tmp_path') . (empty($sPath) ? DS . 'error_path' : DS . $sPath);
        
        if (JFolder::exists($sRootFolder)) {
            return JFolder::delete($sRootFolder);
        }
        return true;
    }
    
    public static function getOrderingFieldOfTable($iTableId) {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('*')
                ->from('#__auto_field')
                ->where('table_id = ' . (int) $iTableId)
                ->where('is_ordering_field = 1');

        $db->setQuery($query);

        try {
            $oOrderingField = $db->loadObject();
        } catch (RuntimeException $e) {
            JError::raiseWarning(500, $e->getMessage);
        }

        return $oOrderingField;
    }

    /**
     * Save file to path.
     * @param string $sFileName
     * @param string $sContent
     * @param string $sPath
     */
    public static function saveFile($sFileName, $sContent, $sPath = '') {
        $oApp = JFactory::getApplication('administrator');
        $sRootFolder = $oApp->getCfg('tmp_path') . (empty($sPath) ? DS . 'error_path' : DS . $sPath);

        if (!JFolder::exists($sRootFolder))
        {
            // Create folder
            JFolder::create($sRootFolder, 0777);
        }
        
        // Create a file.
        $sFilePath = empty($sFileName) ? $sRootFolder . DS . 'error_file_name.txt' : $sRootFolder . DS . $sFileName;
        $sContent = empty($sContent) ? 'error content' : $sContent;

        JFile::write($sFilePath, $sContent, true);
        if (JFile::exists($sFilePath)) {
            // Change the permission.
            chmod($sFilePath, 0777);
        }
    }

    public static function appendFile($sFileName, $sNewContent, $sPath = '') {
        $oApp = JFactory::getApplication('administrator');
        $sRootFolder = $oApp->getCfg('tmp_path') . (empty($sPath) ? DS . 'error_path' : DS . $sPath);

        $sFilePath = empty($sFileName) ? $sRootFolder . DS . 'error_file_name.txt' : $sRootFolder . DS . $sFileName;

        if (!JFile::exists($sFilePath)) {
            self::saveFile($sRootFolder, $sNewContent, $sPath);

            return;
        }

        // Create folder
        $sOldContent = JFile::read($sFilePath);

        if ($sOldContent === false) {
            self::saveFile($sRootFolder, $sNewContent, $sPath);

            return;
        }

        $sContent = $sOldContent . chr(13) . $sNewContent;

        JFile::write($sFilePath, $sContent, true);

        if (JFile::exists($sFilePath)) {
            // Change the permission.
            chmod($sFilePath, 0777);
        }
    }

    /**
     * Zip code to the file.
     * @param string $sTempComponentPath The folder directory that keep the temp file after generate code.
     * @param string $sFileName File name with zip type. Ex: com_google.zip
     * 
     * @see JArchiveZip
     */
    public static function zipComponent($sTempComponentPath, $sFileName) {
        jimport('joomla.filesystem.archive');

        $oApp = JFactory::getApplication('administrator');
        $sTempComponentPath = $oApp->getCfg('tmp_path') . DS . $sTempComponentPath . DS;
        $sZipFile = $oApp->getCfg('tmp_path') . DS . $sFileName;
        
        if (JFile::exists($sZipFile)) {
            JFile::delete($sZipFile);
        }
        
        ini_set("max_execution_time", 300);

        $oZip = new ZipArchive();
        if ($oZip->open($sZipFile, ZIPARCHIVE::CREATE) !== TRUE) {
            return false;
        }
        
        $oIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sTempComponentPath));
        
        foreach ($oIterator as $iKey => $sValue) {
            $iKey = str_replace('\\', '/', $iKey);
            if (!is_dir($iKey)) {
                if (!$oZip->addFile(realpath($iKey), substr($iKey, strlen($sTempComponentPath)))) {
                    return false;
                }
            }
        }
        
        $oZip->close();
        
        if (JFile::exists($sZipFile))
        {
            // Change the permission.
            chmod($sZipFile, 0777);
        }
    }

    public static function forceDownload($sFileName) {
        $oApp = JFactory::getApplication('administrator');
        $sFilePath = $oApp->getCfg('tmp_path') . (empty($sFileName) ? DS . 'error_path' : DS . $sFileName);
        
        if (JFile::exists($sFilePath)) {
            $sContent = file_get_contents($sFilePath);
            
            JFile::delete($sFilePath);
        } else {
            return false;
        }
        
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$sFileName");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        
        echo $sContent;
        die;
    }
    
}

